package controller;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pojo.Article;
import pojo.User;
import service.UserService;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/User")
public class UserController {

    @Autowired
    private UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户输入账号  按账号查找用户  然后再 比对输入的密码是否正确
     *
     * @param account
     * @return
     */
    @RequestMapping("login.do")
    public String login(@RequestParam("username") String account, @RequestParam("password") String password, HttpSession session, Model model) {
        User login = userService.login(account);
        if (login.getPassword().equals(password)) {
            session.setAttribute("User", login);
            model.addAttribute("LoginUserStatus", "登入成功");
            System.out.println("1");
            return "redirect:/article/queryArtofUser.do";
        }else {
            model.addAttribute("LoginUserStatus","登入失败");
            System.out.println("2");
            return "signup";
        }
    }

    /**
     * 多条件查询    查询所有  按昵称模糊查询 按id查询单个用户
     *
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("getAllUser.do")
    public String getAllUser(User user, Model model) {
        System.out.println(user.getId());
        List<User> allUser = userService.getAllUser(user);
        for (User userFor : allUser) {
            System.out.println(userFor);
        }
        model.addAttribute("UserList", allUser);
        return "myinfo";
    }
    /**
     * 用户注册 注册字段 account,password,telephone,status
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/Phonelogin.do")
    @ResponseBody
    public Map<String,Object> addUser(String code, User user, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        if (session.getAttribute("code") == null) {
            map.put("msg", "验证码不存在");
        } else {
            String oldCode = session.getAttribute("code").toString();
            if (oldCode.equals(code)) {
                map.put("msg", "ok");
            } else {
                map.put("msg", "验证码不正确");
            }
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String birthday = df.format(new Date());
        user.setHeadphoto("1573440206(1).png");
        user.setBackphoto("1573440755(1).png");
        user.setGender(2);
        user.setBirthday(birthday);
        user.setBeclick(0);
        user.setBereport(0);
        user.setExp(0);
        user.setLevel(1);
        user.setNickname(user.getAccount()+"@zhihu.com");
        user.setStatus(2);
        userService.addUser(user);
        System.out.println("=================前台获取的User对象：" + user);
        return map;
    }
    /**
     * 用户修改个人信息 动态修改
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "updateUser", method = RequestMethod.POST)
    public String updateUser(@RequestParam("genderString") String genderString, User user, Model model, @RequestParam(required = false) MultipartFile back, @RequestParam(required = false) MultipartFile head, HttpServletRequest request) {

        if (back != null) {
            // 获取上传路径
            // String realPath = request.getServletContext().getRealPath("UserBackPhoto");
            String realPath = request.getServletContext().getRealPath("file" + File.separator + "upload" + File.separator + "UserBackPhoto");
            // 获取源文件名
            String oldFileName = back.getOriginalFilename();
            if(oldFileName!="") {
                // 获取源文件扩展名
                String extension = FilenameUtils.getExtension("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + oldFileName);
                for (int i = 0; i < 5; i++) {
                    System.out.println(extension);
                }
                // 生成新的文件名
                String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "UserBackPhoto.jpg";
                // 封装成File对象
                File file = new File(realPath, fileName);
                try {
                    back.transferTo(file);
                    user.setBackphoto(fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (head != null) {
            // 获取上传路径
            String realPath = "D:/haoen/zhihu/src/main/webapp/UserHeadPhoto/";
            // 获取源文件名
            String oldFileName = head.getOriginalFilename();
            if(oldFileName!="") {
                // 获取源文件扩展名
                String extension = FilenameUtils.getExtension(oldFileName);
                // 生成新的文件名
                String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "UserHeadPhoto.jpg";
                // 封装成File对象
                File file = new File(realPath, fileName);
                try {
                    head.transferTo(file);
                    user.setHeadphoto(fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(genderString.equals("男")){
            user.setGender(2);
        }else if (genderString.equals("女")){
            user.setGender(1);
        }
        System.out.println("前台页面获取的对象：" + user);
        int i = userService.updateUser(user);
        if (i > 0) {
            model.addAttribute("updateUserStatus", "修改成功");
            return "redirect:/User/updateUserMessage.do";
        } else {
            model.addAttribute("updateUserStatus", "修改失败");
            return "individual";
        }
    }


    /**
     * 用户点赞
     *
     * @param beclick 用户被点赞的总数
     * @param id      被点赞的用户id
     * @return
     */
    @RequestMapping("clickToUser")
    public String clickToUser(@RequestParam("beclick") int beclick, @RequestParam("id") int id, Model model) {
        int i = userService.clickToUser(beclick + 1, id);
        if (i > 0) {
            model.addAttribute("updateUserStatus", "点赞成功");
            return "";
        } else {
            model.addAttribute("updateUserStatus", "点赞失败");
            return "";
        }
    }

    /**
     * 查询所有好友  单个好友
     *
     * @param userId   用户本人id
     * @param friendid 好友id
     * @return
     */
    @RequestMapping("getAllfirnd")
    public String getAllfirnd(@RequestParam("userId") int userId, @RequestParam("friendid") int friendid, Model model) {
        List<User> allfirnd = userService.getAllfirnd(userId, friendid);
        if (allfirnd != null) {
            model.addAttribute("firndList", allfirnd);
            model.addAttribute("getAllfirndStatus", "查询成功");
            return "";
        } else {
            model.addAttribute("getAllfirndStatus", "好友为空");
            return "";
        }
    }

    /**
     * 举报用户
     *
     * @return
     * @Param bereport用户被举报的总数量
     * @Param 要举报的用户id
     */
    @RequestMapping("reportUser.do")
    public String reportUser(@RequestParam("bereport") int bereport, @RequestParam("id") int id, Model model) {
        int i = userService.reportUser(bereport + 1, id);
        if (i > 0) {
            model.addAttribute("reportUserStatus", "举报成功");
            return "";
        } else {
            model.addAttribute("reportUserStatus", "举报失败");
            return "";
        }
    }

    /**
     * 短信验证
     *
     * @param phone
     * @param session
     * @return
     */
    @RequestMapping("/sendSMS.do")
    @ResponseBody
    public Map<String, Object> sendSMS(String phone, HttpSession session) {
        System.out.println("发送短信");
        Map<String, Object> map = new HashMap();
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        session.setAttribute("code", code);
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4Fjx6DhfWYS883yGoUTY", "w060ucohXsGMK9AsrkhEcJN3wztESI");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "机器人熊二");
        request.putQueryParameter("TemplateCode", "SMS_175539436");
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            map.put("msg", "ok");
        } catch (ServerException e) {
            e.printStackTrace();
            map.put("msg", e.getMessage());
        } catch (ClientException e) {
            e.printStackTrace();
            map.put("msg", e.getMessage());
        }
        return map;
    }
    /**
     * 刷新个人资料信息
     * @return
     */
    @RequestMapping("/updateUserMessage.do")
    public String updateUserMessage(HttpSession session,HttpServletRequest request){
        System.out.println("刷新个人资料");
        User u = (User) session.getAttribute("User");
        User user = userService.updateUserMessage(u.getUid());
        session.setAttribute("User",user);
        return "myinfo";
    }


    @RequestMapping("/exit.do")
    public String userexit(HttpServletRequest request){
        request.getSession().invalidate();
        return "redirect:/jsp/signup.jsp";
    }

    @RequestMapping(value = "/uploadBackPhoto.do",method = RequestMethod.POST)
    @ResponseBody
    public String uploadBackPhoto(HttpServletRequest request,@RequestParam(required = false) MultipartFile uploadBackPhotoFile, HttpSession session){
        User user = new User();
        Map<String,Object> map = new HashMap<String,Object>();
        if(uploadBackPhotoFile!=null){
            if(uploadBackPhotoFile.getSize()>1*1024*1024){
                map.put("msg","文件大小不能超过100B");
                map.put("status","error");
                map.put("fileName","");
                return JSON.toJSONString(map);
            }

            String realPath = request.getServletContext().getRealPath("file" + File.separator + "upload" + File.separator + "UserBackPhoto");
            //获取原文件名
            String oldFileName=uploadBackPhotoFile.getOriginalFilename();
            //获取扩展名
            String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
            List<String> prefixs=new ArrayList<>();
            prefixs.add("jpg");
            prefixs.add("JPG");
            prefixs.add("png");
            prefixs.add("jpeg");
            prefixs.add("pneg");
            if (prefixs.contains(prefix)==false) {
                map.put("msg", "上传图片格式不正确");
                map.put("status", "error");
                map.put("filename", "");
                System.out.println("上传失败");
                return JSON.toJSONString(map);
            }
            //生成新文件名
            String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"UserBackPhoto.jpg";
            System.out.println(fileName);
            //封装文件对象
            File targetFile = new File(realPath, fileName);
            try {
                uploadBackPhotoFile.transferTo(targetFile);
                map.put("status", "true");
                map.put("msg", "文件上传成功");
                map.put("filename", fileName);
                user.setBackphoto(fileName);
                User id = (User) session.getAttribute("User");
                user.setId(id.getId());
                int i = userService.updateUser(user);
                System.out.println("上传成功");
                return JSON.toJSONString(map);
            } catch (IOException e) {
                e.printStackTrace();
                map.put("status", "error");
                map.put("msg", e.getMessage());
                map.put("filename", "");
                System.out.println("上传失败");
                return JSON.toJSONString(map);
            }

        }
        return JSON.toJSONString(map);
    }
    @RequestMapping(value = "/uploadHeadPhoto.do",method = RequestMethod.POST)
    @ResponseBody
    public String uploadHeadPhoto(HttpServletRequest request,@RequestParam(required = false) MultipartFile uploadHeadPhotoFile, HttpSession session){
        User user = new User();
        Map<String,Object> map = new HashMap<String,Object>();
        if(uploadHeadPhotoFile!=null){
            if(uploadHeadPhotoFile.getSize()>1*1024*1024){
                map.put("msg","文件大小不能超过100B");
                map.put("status","error");
                map.put("fileName","");
                return JSON.toJSONString(map);
            }

            String realPath = request.getServletContext().getRealPath("file" + File.separator + "upload" + File.separator + "UserHeadPhoto");
            //获取原文件名
            String oldFileName=uploadHeadPhotoFile.getOriginalFilename();
            //获取扩展名
            String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
            List<String> prefixs=new ArrayList<>();
            prefixs.add("jpg");
            prefixs.add("JPG");
            prefixs.add("png");
            prefixs.add("jpeg");
            prefixs.add("pneg");
            if (prefixs.contains(prefix)==false) {
                map.put("msg", "上传图片格式不正确");
                map.put("status", "error");
                map.put("filename", "");
                System.out.println("上传失败");
                return JSON.toJSONString(map);
            }
            //生成新文件名
            String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"UserBackPhoto.jpg";
            System.out.println(fileName);
            //封装文件对象
            File targetFile = new File(realPath, fileName);
            try {
                uploadHeadPhotoFile.transferTo(targetFile);
                map.put("status", "true");
                map.put("msg", "文件上传成功");
                map.put("filename", fileName);
                user.setHeadphoto(fileName);
                User id = (User) session.getAttribute("User");
                user.setId(id.getId());
                int i = userService.updateUser(user);
                System.out.println("上传成功");
                return JSON.toJSONString(map);
            } catch (IOException e) {
                e.printStackTrace();
                map.put("status", "error");
                map.put("msg", e.getMessage());
                map.put("filename", "");
                System.out.println("上传失败");
                return JSON.toJSONString(map);
            }

        }
        return JSON.toJSONString(map);
    }

    /**
     * 用户收藏的所有文章存入session域
     * @param id
     * @return
     */
    @RequestMapping("getArticlesByUser.do")
    public String getArticlesByUser(int id,HttpSession session){
        List<Article> articlesByUser = userService.getArticlesByUser(id);
        session.setAttribute("articlesByUserList",articlesByUser);
        return "myinfo";
    }
}